package org.example.mall.admin.service.manage.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.example.mall.admin.mapper.manage.SysTreeMapper;
import org.example.mall.admin.mapper.manage.TreeRelationMapper;
import org.example.mall.admin.model.entity.manage.SysTree;
import org.example.mall.admin.model.entity.manage.TreeRelation;
import org.example.mall.admin.service.manage.SysFileService;
import org.example.mall.admin.service.manage.TreeRelationService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 树层级关系 服务实现类
 * </p>
 *
 * @author hzq
 * @since 2022-01-08
 */
@Service
@AllArgsConstructor
public class TreeRelationServiceImpl extends ServiceImpl<TreeRelationMapper, TreeRelation> implements TreeRelationService {

    private final SysTreeMapper sysTreeMapper;

    @Override
    public Boolean addRelation(SysTree sysTree) {
        // 增加关系表
        List<TreeRelation> relations = list(Wrappers.<TreeRelation>query()
                .lambda().eq(TreeRelation::getChildrenId, sysTree.getParentId()))
                .stream().map(relation -> {
                    relation.setChildrenId(sysTree.getTreeId());
                    return relation;
                }).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(relations)) {
            saveBatch(relations);
        }
        // 自己也要维护到关系表中
        TreeRelation relation = new TreeRelation();
        relation.setParentId(sysTree.getTreeId());
        relation.setChildrenId(sysTree.getTreeId());
        boolean save = save(relation);
        setSysTreeHierarchy(sysTree.getTreeId());
        return save;
    }

    @Override
    public void editRelation(TreeRelation relation) {
        getBaseMapper().editRelation(relation);
        setSysTreeHierarchy(relation.getChildrenId());
    }

    @Override
    public void delRelation(Integer sysTreeId) {
        getBaseMapper().delRelation(sysTreeId);
    }

    // 设置分类树层级
    void setSysTreeHierarchy(Integer treeId) {
        // 获取所有子节点
        list(Wrappers.<TreeRelation>lambdaQuery().eq(TreeRelation::getParentId, treeId))
                .stream().map(TreeRelation::getChildrenId).forEach(childrenId -> {
            // 设置子节点层级
            int hierarchy = count(Wrappers.<TreeRelation>lambdaQuery().eq(TreeRelation::getChildrenId, childrenId));
            SysTree sysTree = new SysTree();
            sysTree.setTreeId(childrenId).setHierarchy(hierarchy);
            sysTreeMapper.updateById(sysTree);
        });
    }
}
